<?php

include_once 'AdminController.php';

class main extends AdminController{

	private $_api = '';

	function __construct(){
		parent::__construct(); 
        
        //$this->_D($_SERVER['HTTP_USER_AGENT']);
        
        if ( strpos($_SERVER['HTTP_USER_AGENT'], 'MicroMessenger') == false ) { 
            exit('只能通过微信访问');
        }
        include_once 'api.php';
    	$this->_api = spClass('api'); 
    	$this->Project = Project;
	}

	function index(){ 
		$openid = $_SESSION['openid']; 
		if(empty($openid)){
			header('location:/'.Project.'/index.php/main/oauth');
		}
		$wxinfo = $_SESSION['user_info'];
		$this->ShareImage = $wxinfo['headimgurl'];
	}

	function pv(){}
	
	function testIndex(){
		header('location:/'.Project.'/index.php/main/oauth?oauthbackurl='.urlencode('/main/testlogin'));
	}
	
	function getjsConf(){
		$url = $_REQUEST['url'];
		$config = $this->_api->getShareConfig($url); 
		$this->_JSON($config);
	}
	
	function share(){
		$acid = $this->spArgs('acid');
		if(empty($acid)){
			exit('请求参数错误');
		}	
		$acModel = spClass('bl_active');
		$active = $acModel->find(array('id'=>$acid));
		
		$openid = $_SESSION['openid']; 
		if(empty($openid)){
			header('location:/'.Project.'/index.php/main/oauth?oauthbackurl='.urlencode('/main/share/acid/'.$acid));
		}
		if(empty($active)){
			exit('请求参数错误');
		}
		$this->active = $active;
		 
		$uModel = spClass('wx_user');
		$wxinfo = $uModel->find(array('openid'=>$active['openid']));
		$this->ShareImage = $wxinfo['headimgurl'];
		
		$alModel = spClass('bl_activelog');
		$hasgive = $alModel->find(array('act_id'=>$acid,'openid'=>$openid));
		$this->hasgive = empty($hasgive)?false:true;
	}
	
	function checkHasGive(){
		$acid = $this->spArgs('acid');
		$openid = $_SESSION['openid']; 
		if(empty($acid)){
			exit('请求参数错误');
		}	
		if(empty($openid)){
			exit('请求参数错误');
		}
		$alModel = spClass('bl_activelog');
		$hasgive = $alModel->find(array('act_id'=>$acid,'openid'=>$openid));
		if(!empty($hasgive)){
			$this->_JSON(array('s'=>true));
		}
		$this->_JSON(array('s'=>false));
	}
	
	/**
	* 获取我所获得的阳光值
	* @return
	*/
	function getMyFlower(){
		$acid = $this->spArgs('acid');
		$openid = $_SESSION['openid'];
		if(empty($openid)){
			$this->_JSON(array('s'=>false,'m'=>'缺少必要参数'));
		}
		$aModel = spClass('bl_active');
		if(empty($acid)){
			$active = $aModel->find(array('openid'=>$openid));
		}else{
			$active = $aModel->find(array('id'=>$acid));
		}
		
		if($active){
			$this->_JSON(array('s'=>true,'m'=>'','d'=>$active));
		}else{
			$this->_JSON(array('s'=>false,'m'=>'你还没有发起活动'));
		}
	}

	/**
	* 发起一次活动
	* @return
	*/
	function createactive(){
		$openid = $_SESSION['openid'];
		if(empty($openid)){
			$this->_JSON(array('s'=>false,'m'=>'缺少必要参数'));
		}
		$aModel = spClass('bl_active');
		$data = array(
			'openid'=>$openid
		);
		
		$active = $aModel->find($data);
		if(empty($active) || count($active)<1){
			$active = $aModel->create($data);
		}
		if($active){
			$this->_JSON(array('s'=>true,'m'=>'','d'=>$active));
		}else{
			$this->_JSON(array('s'=>false,'m'=>'发起活动失败'));
		}
	}
	
	/**
	* 授权登陆
	* @return
	*/
	function oauth(){ 
		if($_GET['oauthbackurl']){ 
			$_SESSION['oauthbackurl'] = $_GET['oauthbackurl'];
		}
		$callback = '/'.Project.'/index.php/main/oauthback';
		$oauthurl = $this->_api->getOauthUrl($callback);
		header('location:'.$oauthurl);
	}
	
	/**
	* 授权回调地址
	* @return
	*/
	function oauthback(){ 
		$rs = $this->_api->oauthback();
		$uModel = spClass('wx_user'); 
		$uinfo = $uModel->find(array('openid'=>$rs['openid']));
		if(empty($uinfo) || count($uinfo)<1){ 
			$st = $uModel->create($rs);
		}  
		
		$_SESSION['user_info'] = $rs;
		$_SESSION['openid'] = $rs['openid'];
		
		if($_SESSION['oauthbackurl']){
			$toUrl = $_SESSION['oauthbackurl'];
			$_SESSION['oauthbackurl'] = NULL; 			
			header('location:/'.Project.'/index.php'.$toUrl);
			exit();
		}  
		
		header('location:/'.Project.'/index.php/main/index'); 
		exit();
	}
	
	
	function giveSunShine(){
        $this->_JSON(array('s'=>false,'m'=>'活动已结束'));
		$acid = $this->spArgs('acid');
		if(empty($acid)){
			$this->_JSON(array('s'=>false,'m'=>'参数错误'));
		}
		$openid = $_SESSION['openid'];
		$aModel = spClass('bl_active');
		$active = $aModel->find(array('id'=>$acid));
		if($active['openid']==$openid){
			$this->_JSON(array('s'=>false,'m'=>'不能给自己阳光'));
		}
		$alModel = spClass('bl_activelog');
		$log = $alModel->find(array('openid'=>$openid,'act_id'=>$acid));
		if(!empty($log)){
			$this->_JSON(array('s'=>false,'m'=>'你已给过阳光'));
		}
		$user = $_SESSION['userinfo'];
        if(empty($openid)){
    		$this->_JSON(array('s'=>false,'m'=>'你未登陆，无权操作'));
		}
		$fid = mt_rand(1,1000);
		$fid = $fid%5+1;
		//保存日志文件
		$data = array(
			'act_id'	=>	$acid,
			'user_id'	=>	$user['id'],
			'openid'	=>	$openid,
			'act_id'	=>	$acid,
			'f_name'	=>	$fid,
		);
		$rs = $alModel->create($data);
		//更新活动状态 
		$aModel = spClass('bl_active');
		$ac = $aModel->find(array('id'=>$acid));
		$aModel->update(array('id'=>$acid),array('f'.$fid => 1,'f_count'=>$ac['f_count']+1));
		$this->_JSON(array('s'=>true,'m'=>'','d'=>$fid));
	}
	
	/**
	* 获取排行榜数据
	* @return
	*/
	function getPHBList(){
		$aModel = spClass('bl_active'); 
		$uModel = spClass('wx_user');
		$list = $aModel->findAll(null,'f_count desc',null,24);
		$openid = $_SESSION['openid'];
		$active = $aModel->find(array('openid'=>$openid));
		$active['user'] = $uModel->find(array('openid'=>$openid)); 
		$nm = $active['user']['nickname'];
		$active['user']['nickname'] = strlen($nm)>3?mb_substr($nm,0,3,'utf-8').'.':$nm;
		$paiming = $aModel->findCount(' f_count>'.$active['f_count']);
		$active['paiming'] = $paiming+1;
		$datlist = array();
		foreach($list as $it){
			$tarr = $it;
			$tarr['user'] = $uModel->find(array('openid'=>$it['openid']));
			if(strlen($tarr['user']['nickname'])>6){
				$tarr['user']['nickname'] = mb_substr($tarr['user']['nickname'],0,6,'utf-8').'...';
			}
			$datlist[] = $tarr;
		}
		$this->_JSON(array('s'=>true,'m'=>'','d'=>array(
			'my'	=>	$active,
			'list'	=>	$datlist,
		)));
	}
	
	/**
	* 获取阳光值日志
	* @return
	*/
	function getLGList(){
		$openid = $_SESSION['openid'];
		$aModel = spClass('bl_active');
		$alModel = spClass('bl_activelog');
		$uModel = spClass('wx_user');
		$active = $aModel->find(array('openid'=>$openid)); 
		$list = $alModel->findAll(array('act_id'=>$active['id']));
		$datlist = array();
		foreach($list as $it){
			$tarr = $it;
			$tarr['timestr'] = date('Y-m-d',strtotime($it['created']));
			$tarr['user'] = $uModel->find(array('openid'=>$it['openid']));
			$datlist[] = $tarr;
		}
		$this->_JSON(array('s'=>true,'m'=>'','d'=>$datlist));
	}
	 
	/**
	* 检验OPENID登陆
	* @return
	*/
	function loginby3rdopenid(){
		$openid = $_SESSION['openid'];  
		if($_GET['openid']){
			$openid = $_GET['openid'];
		}
		$phone = '';
		$serivceName =  APIURL::$_loginby3rdopenid;
		//设置业务参数
		$parm = array(
			'third_party_id'	=>	$openid,
			'third_party_id_type'	=>	1 ,
			'third_party_appid'	=>	WX_Config::$third_party_appid,
		);   
		$data = $this->_api->doServicePost($serivceName,$parm);  
		$this->savelog($serivceName,$parm,$data);
		$isNewUser = true;
		if($data['resCode'] == '00100000'){
			$_SESSION['userinfo'] = $data['obj'];
			$isNewUser = false;
			$phone = $data['obj']['mobile'];
		}
		$this->_JSON(array('isNewUser'=>$isNewUser,'phone'=>$phone));
	}
	
	
	function testlogin(){
		$this->_D($_SESSION,false);
		$openid = 'oG_0-uMpemfKTutflmGysrl7ZRnQ';
		$_SESSION['openid'] = $openid;
		$token = $_SESSION['config_data']['access_token'];
		$user = $this->_api->getuserInfo($openid,$token);
		$this->_D($user);
		//$this->loginby3rdopenid();
	}
	
	function checkhasguanzhu(){
		$openid = $_SESSION['openid'];
		$token = $_SESSION['config_data']['access_token']; 
		$user = $this->_api->getuserInfo($openid,$token);
		$gz = true;
		if(isset($user['subscribe']) && $user['subscribe']==0) {
			$gz = false;
		}
		$this->_JSON(array('s'=>$gz));
	}
	
	/**
	* 检验OPENID登陆
	* @return
	*/
	function loginby3rdopenid2($openid){ 
		$serivceName =  APIURL::$_loginby3rdopenid;
		//设置业务参数
		$parm = array(
			'third_party_id'	=>	$openid,
			'third_party_id_type'	=>	1 ,
			'third_party_appid'	=>	WX_Config::$third_party_appid,
		);   
		$data = $this->_api->doServicePost($serivceName,$parm);  
		$this->savelog($serivceName,$parm,$data);
		$isNewUser = true;
		if($data['resCode'] == '00100000'){
			$_SESSION['userinfo'] = $data['obj'];
			$isNewUser = false;
		}
	}
	
	function logout(){
		session_destroy();
		//header('location:/'.Project.'/index.php/main/index'); 
	}
	
	/**
	* 检验手机号码
	* @return
	*/
	function checkphone(){
		$phone = $_REQUEST['phone'];
		if(empty($phone) || strlen($phone)!=11){
			$this->_JSON(array('errCode'=>'nicky001','msg'=>'手机号码输入有误'));
		}
		$serivceName =  APIURL::$_checkphone;
		//设置业务参数
		$parm = array(
			'login_Id'	=>	$phone,
			'sysid'		=> WX_Config::$sysid,
		);
		
		$data = $this->_api->doServicePost($serivceName,$parm);
		$this->savelog($serivceName,$parm,$data);
		$this->_JSON($data);
	}
	
	function _JSON($data){
		exit(json_encode($data));
	}
	
	/**
	* 发送注册手机验证码 
	*/
	function sendregistercode(){
		$phone = $_REQUEST['phone'];
		if(empty($phone) || strlen($phone)!=11){
			$this->_JSON(false,'手机号码输入有误');
		}
		$serivceName =  APIURL::$_sendregistercode;
		//设置业务参数
		$parm = array(
			'mobile'	=>	$phone,
			'sysid'		=> WX_Config::$sysid,
		);
		$data = $this->_api->doServicePost($serivceName,$parm);
		$this->savelog($serivceName,$parm,$data);
		$this->_JSON($data);
	}
	
	//手机验证码登录短信下发
	function sendlogincode(){ 
		$phone = $_REQUEST['phone'];
		if(empty($phone) || strlen($phone)!=11){
			$this->_JSON(false,'手机号码输入有误');
		}
		$serivceName =  APIURL::$_sendlogincode;
		//设置业务参数
		$parm = array(
			'mobile'	=>	$phone,
			'sysid'		=> WX_Config::$sysid,
		);
		$rs = $this->_api->doServicePost($serivceName,$parm);
		$this->savelog($serivceName,$parm,$rs);
		$this->_JSON($rs);
	} 
	 
	function weixinregisterandbind(){ 
		$openid = $_SESSION['openid'];
		if($_GET['openid']){
			$openid = $_GET['openid'];
		}
		$phone = $_REQUEST['phone'];
		if(empty($phone) || strlen($phone)!=11){
			$this->_JSON(false,'手机号码输入有误');
		}
		$smsCode = $_REQUEST['smsCode'];
		if(empty($smsCode) ){ 
			$this->_JSON(false,'验证码输入有误');
		}
		$serivceName =  APIURL::$_weixinregisterandbind;
		//设置业务参数
		$parm = array(
			'openId'	=>	$openid,
			'smsCode'	=>	$smsCode,
			'loginId'	=>	$phone,
			'mobile'	=>	$phone,
			'sysid'		=>	WX_Config::$sysid,
		); 

		$data = $this->_api->doServicePost($serivceName,$parm);
		$this->savelog($serivceName,$parm,$data);
		$this->loginby3rdopenid2($openid);

		$this->_JSON($data);
	}
	
	/**
	* 微信登陆及手机绑定手机
	* 测试OK
	*/
	function weixinloginandbind(){
		$openid = $_SESSION['openid'];
		if($_GET['openid']){
			$openid = $_GET['openid'];
		}
		$phone = $_REQUEST['phone'];
		if(empty($phone) || strlen($phone)!=11){
			$this->_JSON(array('resCode'=>'nicky0001','msg'=>'手机号码输入有误'));
		}  
		$smsCode = $_REQUEST['smsCode'];
		if(empty($smsCode) ){
			$this->_JSON(array('resCode'=>'nicky0002','msg'=>'验证码输入有误')); 
		}
		$serivceName =  APIURL::$_weixinloginandbind;
		//设置业务参数
		$parm = array(
			'openId'	=>	$openid,
			'smsCode'	=>	$smsCode,
			'loginId'	=>	$phone,
			'mobile'	=>	$phone,
			'sysid'		=>	WX_Config::$sysid,
			'loginType'	=>	WX_Config::$loginType,
		);
		$data = $this->_api->doServicePost($serivceName,$parm);
		
		$this->savelog($serivceName,$parm,$data);
		
		$this->loginby3rdopenid2($openid);
		
		$this->_JSON($data);
	}
	
	function sendCoupon(){ 
		$openid = $_SESSION['openid']; 
		$serivceName =  APIURL::$_send;
		$tokendata = $this->_api->getToken();
		$membetToken = $_SESSION['userinfo']['member_token']; 
		$memberLevel = $_SESSION['userinfo']['memberLevel']; 
		//设置业务参数
		$parm = array(
			'memberToken'	=>	$membetToken,
			'eventTypeId'	=>	WX_Config::$eventTypeId,
			'memberRank'	=>	$memberLevel,
			'channelId'		=>	WX_Config::$channelId,
			'businessId'	=>	WX_Config::$businessId, 
		); 
		$data = $this->_api->doServicePost2($serivceName,$parm); 
		$this->savelog($serivceName,$parm,$data); 
		$obj = $data['obj'];
		$ct = empty($obj)?-1:(empty($obj[count($obj)-1]['couponCount'])?-1:$obj[count($obj)-1]['couponCount']);
		if($data['resCode']=='00100000'){
			
			//更新领券状态
			$acModel = spClass('bl_active');
			$acModel->update(array('openid'=>$openid),array('status'=>2));
			
		}
		$this->_JSON($data); 
	}
	
	function saveCouponLog($data){
		$count = 0;
		$obj = $data['obj'];
		$ct = empty($obj)?0:(empty($obj[count($obj)-1]['couponCount'])?0:$obj[count($obj)-1]['couponCount']);
		$savedata = array(
			'openid'	=>	$_SESSION['openid'],
			'member_token'	=>	$membetToken,
			'couponCount'	=>	$ct,
			'content'	=>	json_encode($data),
		);
		$logModel = spClass('coupon_log'); 
		//保存到数据库
		$rs = $logModel->create($savedata); 
	}
	 
	
	function savelog($serviceName,$parm,$response){
		$logModel = spClass('api_log');
		$data = array(
			'servicename'	=>	$serviceName,
			'parm'			=>	json_encode($parm),
			'response'			=>	json_encode($response),
		);
		$logModel->create($data);
	}
	
}